const { isFunction, isArray, isString, isObject } = require('./utils');

const handleAsset = (op, data) => {
  let ret = data;
  if (isString(op)) {
    ret.push(op);
  }
  if (isArray(op)) {
    op.forEach((item) => {
      if (isObject(item)) {
        if (item.pos === 'pre') {
          ret.unshift(item.path);
        } else {
          ret.push(item.path);
        }
      } else if (isString(item)) {
        ret.push(item);
      }
    });
  }
  if (isObject(op)) {
    if (op.pos === 'pre') {
      ret.unshift(op.path);
    } else {
      ret.push(op.path);
    }
  }
  if (isFunction(op)) {
    ret = op(data);
  }
  return ret;
};

function HandleInjectHtmlWebpackPlugin (opt) {
  this.opt = opt;
}

HandleInjectHtmlWebpackPlugin.prototype.apply = function (compiler) {
  compiler.plugin('compilation', (compilation, options) => {
    compilation.plugin('html-webpack-plugin-before-html-processing', (data, callback) => {
      if (this.opt.js) {
        data.assets.js = handleAsset(this.opt.js, data.assets.js);
      }
      if (this.opt.css) {
        data.assets.css = handleAsset(this.opt.css, data.assets.css);
      }
      callback(null, data);
    });
  });
};

module.exports = HandleInjectHtmlWebpackPlugin;
